import { reqgetgoods } from "../../http/api"
import { reqgetcate } from "../../http/api"

const initState ={
    catelist:[],
    goodslist:[],
    fid:1
}

const types = {
    CHANGE_CATELIST:"CATE_CHANGE_CATELIST",
    CHANGE_GOODSLIST:"CATE_CHANGE_GOODSLIST",
    CHANGE_PAGE:"CATE_CHANGE_PAGE"
}

const reducer = (state = initState,action)=>{
    switch(action.type){
        case types.CHANGE_CATELIST:
            return{
                ...state,
                catelist:action.catelist
            }
        case types.CHANGE_GOODSLIST:
            return{
                ...state,
                goodslist:action.goodslist
            }
        case types.CHANGE_PAGE:
            return{
                ...state,
               fid:action.fid
            }
        default:
            return state
    }
}

/* 逻辑 */
export const actions = {
    changeCatelist: catelist => ({type:types.CHANGE_CATELIST,catelist}),
    reqgetcate:()=>(dispatch,getStart)=>{
        reqgetcate().then(res=>{
            if(res.data.code === 200){
                dispatch(actions.changeCatelist(res.data.list))
                dispatch(actions.reqgetgoods(res.data.list[0].id))
            }
        })
    },
    changeGoodslist: goodslist =>({type:types.CHANGE_GOODSLIST,goodslist}),
    reqgetgoods:(fid)=>(dispatch,getStart)=>{
        reqgetgoods({fid}).then(res=>{
            if(res.data.code === 200){
                dispatch(actions.changeGoodslist(res.data.list))
            }
        })
    },
    changePage:(fid)=>(dispatch,getState)=>{
        dispatch(actions.reqgetgoods(fid))
    }
}

/* 导出数据 */
export const getCatelist = state => state.Cate.catelist;
export const getGoodslist = state => state.Cate.goodslist;
/* 导出整体 */
export default reducer